<?php
/**
 *待付款订单处理
 *
 * */
class Sale_topayAction extends CommonAction{

    public function _filter(&$map) {
        //TODO
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
             $map['_complex'] = A('Search')->search($key,'Sale_detail','sale_title','Sale_detail.id');
           //$where['Sale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
               // $where['Sale.customer_name'] = array('like',"%".$key."%");//产品名称
           /* 
            $where['_logic'] = "or";
            $map['_complex'] = $where;*/
        }
        if(!empty($_REQUEST['order_no'])) {
            $key2 = trim($_REQUEST['order_no']);
          $map['_string'] = '(sale_no = "'.$key2.'") ';
    }
       //模糊订单号搜索
        if(!empty($_REQUEST['like_order_no'])) {
            $key3 = trim($_REQUEST['like_order_no']);
              $map['_string'] = '(sale_no like "%'.$key3.'%")';
        }

        if( $_REQUEST['remark'] != '' )
          $map['remark'] = trim($_REQUEST['remark']);

        if( $_REQUEST['phone'] != '' )
          $map['phone'] = array('like',"%".trim($_REQUEST['phone'])."%");

        if( $_REQUEST['mobile'] != '' )
          $map['mobile'] = array('like',"%".trim($_REQUEST['mobile'])."%");

        if( $_REQUEST['address'] != '' )
          $map['address'] = array('like',"%".trim($_REQUEST['address'])."%");

        if( $_REQUEST['shipping_name'] != '' )
          $map['shipping_name'] = array('like',"%".trim($_REQUEST['shipping_name'])."%");

        if( $_REQUEST['customer_name'] != '' )
          $map['customer_name'] = array('eq',trim($_REQUEST['customer_name']));

        if( $_REQUEST['order_status'] != '' )
          $map['order_status'] = $_REQUEST['order_status'];
        
        if( $_REQUEST['status'] != '' )
          $map['status'] = $_REQUEST['status'];

        if( $_REQUEST['order_source_id'] != '' )
          $map['order_source_id'] = $_REQUEST['order_source_id'];
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //审核时间
                $map['check_time '] = $cond_time;
                break;
              case '2': //发货时间
                $map['shipping_time '] = $cond_time;
                break;
              case '3': //下单时间
                if (empty($_REQUEST['keywords'])) {
                    
                    if($_REQUEST['etype'] == 'detail' ){ //导出订单详情，需按saleView进行搜索
                      $map['Sale.create_time '] = $cond_time;
                    }else
                      $map['create_time '] = $cond_time;
                }else
                    $map['Sale.create_time '] = $cond_time;
                break;
              case '4': //支付时间
                $map['pay_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

    }

    public function index(){
          $sum_should_pay = M('Sale_topay')->where($map)->sum('should_pay');
          $this->assign('sum_should_pay' ,$sum_should_pay);
          $this->assign('count_to_send',M('Sale_topay')->where('noticed = 0')->count('id'));
          parent::index();
    }

    //批量发短信
    public function send_message(){
         
         if(!empty($_REQUEST['mobile']) && !empty($_REQUEST['msg']) ) {
            //TODO 过滤掉已经催付的订单
            $mobile = trim($_REQUEST['mobile']);
            $msg = trim($_REQUEST['msg'])."【".trim($_REQUEST['shop_name'])."】";
            $t = A('OrderAPI')->sendMessages($mobile,$msg );
            if($t){
              M('Sale_topay')->where('id in('.$_REQUEST['id'].')')->setField('noticed','1');
              $this->success("短信发送成功",false,5);
            }else
              $this->error("短信发送失败，请重新发送！");
         }else{//display
             $count_order_source = M('Sale_topay')->where('id in('.$_REQUEST['id'].')')->count('distinct(order_source_id)');
             if($count_order_source > 1)
                 $this->error('请选择同一订单来源的订单操作!');

              //过滤掉已经催付的订单 
              $map = array(
                  'id' => array('in',$_REQUEST['id']),              
                  'noticed' => 0
              );
              $sale_topays = M('Sale_topay')->where($map)->field('id,customer_name,shipping_name,mobile,create_time,order_source_id,remark')->findAll();

             if(3 == $order_source =  M('Sale_topay')->where('id in('.$_REQUEST['id'].')')->getField('order_source_id')  ){ //京卫订单
                 $clean_topays = array();
                 foreach( $sale_topays as $jwk=> $jw_value ){
                      if($this->is_dyw_order($jw_value['remark']))
                         $clean_topays[$jwk] = $jw_value; //去掉非大眼窝订单                
                 }

                 $sale_topays = $clean_topays;

             }
             $mobiles = array();
             $valid_ids = ""; //有效的订单ID
             foreach( $sale_topays as $k=> $value ){//去重手机号
                if(empty($value['mobile'])) //空手机 号不要
                    continue;
                $mobiles[$k] = $value['mobile'];    
                if($k == 0)
                    $valid_ids .=$value['id'];
                else
                    $valid_ids .=",".$value['id'];
             }
             $mobiles = array_unique($mobiles);
             $mobiles_str = implode(",", $mobiles);

            if(substr($valid_ids,0,1) == "," )
                $valid_ids = substr_replace($valid_ids,'',0,1); //去掉开头的,
             $this->assign('valid_ids',$valid_ids);
             $this->assign('mobiles',$mobiles_str);
             $this->assign('sale_topays',$sale_topays);
              $this->edit('Sale_topay','send_message'); 
             }
            
  }


    //import taobao order
    public function import_order(){
        $inputFileName = A('Import')->getCsv();
        $file_type = $_POST['file_type'];

        $sale_detail = M('Sale_detail');
        $sale = M('Sale_topay');
        $customer = M('Customer');
        $shipping_address = M('Shipping_address');
        $sdata = array(); // get line data from csv
        $i = 0; //统计有多少 条记录成功导入
        //注意：导入字体以gb2312解析，字库不全，繁体及生僻字无法解析，必须使用GBK
        switch ($file_type) {
            case '1':
                $order_source = 3; //京卫订单
                break;
            case '2':
                $order_source = 5;//德生堂订单
                break;
            default:
                break;
        }

           if(!strpos($inputFileName, 'OrderList') ) 
           {
            $this->error('请上传淘宝订单文件，文件名为OrderList字样');
           }
        $row = 1;
        $sale_no_data = array(); //存入订单号

        if (($handle = fopen($inputFileName, "r")) !== FALSE) {
        while (($data = fgetcsv($handle,  0, ',', '"', '"')) !== FALSE) {
            if($row > 1 
                  && (getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) == 1 //等待付款的订单 
                  or getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ) == 0) //待付款的订单 --未创建支付宝交易
                  && $this-> shouldAddOrder( trim($data['0'] ) ) //避免重复导入
                  && is_lens_order(iconv('GBK','utf-8',$data['19']))// 过滤掉非我方订单 
             ) { //start from second line
               $full_address = get_tb_address( trim(iconv('GBK','utf-8',$data['13'])) );
               $sdata = array(
                   'sale_no' => trim($data['0']),
                   'mall_no' => trim($data['0']), //第三方订单号
                   'customer_name' => trim(iconv('GBK','utf-8',$data['1'])),//会员名
                   'alipay' => trim(iconv('GBK','utf-8',$data['2'])),
                   //转化为我方货款
                   'total' =>  trim($data['8']) , 
                   'logifee' => trim($data['4']),
                   'sum_pay' => trim($data['3']), //理论应付款：总金额，有可能包括对方货款
                   'should_pay' => trim($data['3']),    
                   'real_pay' => trim($data['8']),  //买家实际支付金额,可能包含第三方货款
                   // 订单状态转换统一的
                   'order_status' => getOrderStatus(trim(iconv('GBK','utf-8',$data['10'])) ),

                   'customer_msg' => trim(iconv('GBK','utf-8',$data['11'])),
                   'create_time' => strtotime( trim($data['17']) ),
                   'pay_time' => empty($data['18']) ? 0: strtotime( trim($data['18']) ),  //支付时间
                    
                   'is_morder' => trim(iconv('GBK','utf-8',$data['31'])),  //手机订单 

                   //shipping address info
                   'shipping_name' => trim(iconv('GBK','utf-8',$data['12'])),
                   'address' => trim(iconv('GBK','utf-8',$data['13'])),

                   'province' => $full_address['province'], //省份
                   'city' => $full_address['city'], //市
                   'county' => $full_address['county'],  //区或县

                   'phone' => trim(iconv('GBK','utf-8',$data['15'])),
                   'mobile' => fixMobile(trim(iconv('GBK','utf-8',$data['16'])) ),
                   'remark' => trim(iconv('GBK','utf-8',$data['19'])) , //商家备注暂用宝贝标题代替
                   'order_source_id' => $order_source, //宝来源订单
                   'sum_number' => $data['24'],

               );

                   // 新增会员 或获取已有会员ID 淘宝可用
               $customer_id = getCustomerId($sdata['customer_name'],$sdata['alipay'] );
               $sdata['customer_id'] = $customer_id ;
               $shipping_address_id = getShippingAddressId($customer_id ,$sdata['shipping_name'],$sdata['address'],$sdata['mobile'],$sdata['phone'] );
               $sdata['shipping_address_id'] = $shipping_address_id ;
               $sale_id = $sale -> add($sdata);
               
               unset($sdata);
               $i++;
            }
            $row++;
        }
        fclose($handle);
        }

        $this->success("成功导入 ".$i." 条待付款订单",false,5);
        break;
    //end switch

    }

 //检查是否可以写入订单到订单表.表无订单记录,则可以插入,返回true;
   function shouldAddOrder($order_no){
      $sr = M('Sale_topay')->where('sale_no ="'.$order_no.'"')->field('id')->find();
      if( !$sr )
          return true;
      else
          return false;
   }

 //判断是否是大眼窝的产品 ,如果是,则返回true,否则返回false
  private function is_dyw_order($keywords = ""){
        if (empty($keywords))
            return false;
        
        if(strpos($keywords,'海昌') !== false || strpos($keywords,'强生') !== false  || strpos($keywords,'博士伦') !== false ||strpos($keywords,'科莱博') !== false ||  strpos($keywords,'优能') !== false || strpos($keywords,'卡洛尼') !== false|| strpos($keywords,'护理液') !== false || strpos($keywords,'洗眼液') !== false || strpos($keywords,'视康') !== false
            || strpos($keywords,'视康') !== false
            || strpos($keywords,'卫康') !== false
            || strpos($keywords,'保视宁') !== false
            || strpos($keywords,'海俪恩') !== false
            || strpos($keywords,'欧柯莱视') !== false
            || strpos($keywords,'自然美') !== false
            || strpos($keywords,'美星') !== false
            || strpos($keywords,'爱漾') !== false
        )
           return true;
        return false;
  }

    
}
?>
